#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import re
import sys
import time
import signal
import sqlite3
import argparse
import logging
import logging.handlers
from utils.ipip import IP

logger = logging.getLogger('ipstat')

IP.load(os.path.join(sys.path[0], 'data/17monipdb.dat'))


def exit_handler(signal, frame):
    sys.exit()


def time_converter(secs):
    # Asia/Shanghai
    return time.gmtime(secs + 8 * 60 * 60)


def validate_tag(value):
    if not re.match(r'^[a-z0-9]{1,10}$', value):
        raise argparse.ArgumentTypeError('must be in the form "^[a-z0-9]{1,10}$"')
    return value


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--tag', dest='tag', help='ip record category tag [a-z0-9]', type=validate_tag)
    parser.add_argument('-v', '--version', action='version', version='%(prog)s 1.0.0')
    opts = parser.parse_args()

    if not len(sys.argv) > 1:
        parser.print_help()
        sys.exit()

    tag = opts.tag

    signal.signal(signal.SIGINT, exit_handler)
    handler = logging.StreamHandler()
    formatter = logging.Formatter(fmt='[%(asctime)s] %(levelname)s [%(name)s:%(lineno)d] "%(message)s"')
    formatter.converter = time_converter
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    logger.setLevel(logging.DEBUG)

    sqlite_db = os.path.join(sys.path[0], 'data', 'db', 'ipstat.db')
    with open(os.path.join(sys.path[0], 'sqls', 'ipstat.sql'), 'rb') as f:
        sql = f.read()
    conn = sqlite3.connect(sqlite_db, isolation_level=None)
    conn.executescript(sql)
    cursor = conn.cursor()

    while True:
        line = sys.stdin.readline()
        if not line:
            break
        ip = line.strip()
        try:
            assert re.match(r'^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$', ip)
            region = IP.find(ip).strip()
        except Exception as e:
            continue
        cursor.execute('insert into ipstat (ip, region, tag) values (?, ?, ?)', (ip, region, tag))
        logger.info('ip: %s, region: %s, tag: %s', ip, region, tag)


if __name__ == '__main__':
    main()
